package com.java.io.character_stream;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 文件拷贝(字符流操作)
 */
public class CopyFiles {
    /**
     * 只能拷贝 txt 文件，其他文件都乱码了
     * 因为 txt 文件的编码格式是 utf-8
     */
    public void copy_2() {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            fw = new FileWriter("C:\\Users\\xuexa\\Desktop\\xx_copy.txt");
            fr = new FileReader("C:\\Users\\xuexa\\Desktop\\xx.txt");
            char[] buf = new char[1024];
            int len = 0;
            while ((len = fr.read(buf)) != -1) {
                System.out.println(buf);
                fw.write(buf, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException("读写失败");
        } finally {
            if (fr != null)
                try {
                    fr.close();
                } catch (IOException ex) {
                    throw new RuntimeException("释放资源失败");
                }
            if (fw != null)
                try {
                    fw.close();
                } catch (IOException ex) {
                    throw new RuntimeException("释放资源失败");
                }
        }
    }

    //从C盘读一个字符，就往D盘写一个字符。(效率低)
    public void copy_1() throws IOException {
        //创建目的地。
        FileWriter fw = new FileWriter("C:\\Users\\xuexa\\Desktop\\xx_copy.txt");
        //与已有文件关联。
        FileReader fr = new FileReader("C:\\Users\\xuexa\\Desktop\\xx.txt");
        int ch = 0;
        while ((ch = fr.read()) != -1) {
            fw.write(ch);
        }

        fw.close();
        fr.close();
    }

}
